(function() {
    'use strict';

    /**
     * @ngdoc function
     * @name webApp.controller:DistributorCtrl
     * @description
     * # DistributorCtrl
     * Controller of the webApp
     */
    angular.module('webApp')
        .controller('DistributorCtrl', DistributorCtrl);

    DistributorCtrl.$inject = ['$scope', 'dataService', '$state', 'helper', '$location', 'sessionService', '$rootScope', 'cacheService', 'ERP_CONFIG'];

    function DistributorCtrl($scope, dataService, $state, helper, $location, sessionService, $rootScope, cacheService, ERP_CONFIG) {

        $scope.listAction = function() {
            $scope.pageSize = 10;
            $scope.getList();
            $scope.chosedStatus = 0;
            // $scope.getMinimum();
            // $scope.fenxiaoState();
            // $scope.fenxiaoAutoShenPi();
            // $scope.fenxiaoAutoShenQing();
        }


        //回调选择代理商
        $scope.callbackAgent = function(agentInfo) {
            if (agentInfo) {
                $scope.agentInfo = agentInfo;
                console.error("agentInfo", $scope.agentInfo);
            }
        }

        //查询分销商列表
        $scope.getList = function(pageNo) {
            var query = {};
            var key = $rootScope.store_id + "DistributorCtrl";
            var cache = cacheService.get(key);

            if (!cache || pageNo) {
                query = {
                    content: {
                        page_no: pageNo ? pageNo : "1",
                        page_size: $scope.pageSize,
                        store_id: $rootScope.store_id
                    }
                };

                if ($scope.chosedStatus && $scope.chosedStatus != 0) {
                    query.content.status = $scope.chosedStatus;
                }

                query = $scope.getWhere(query);
                var data = clone(query);
                cacheService.set(key, data);
            } else {
                query = clone(cache);
                $scope.getCacheQuery(cache);
            }

            dataService.distributorGet(query).then(function(r) {
                if (r.distributor_list) {
                    $scope.distributorList = r.distributor_list;
                    $scope.totalCount = r.total_count;
                }
            });
        }
        $scope.getDistributorOne = function(cache) {
            var query = {
                content: {
                    "distributor_id": $scope.distributor_id,
                    "store_id": $rootScope.store_id,
                }
            };

            dataService.distributorGet(query).then(function(r) {
                if (r) {
                    $scope.distributorInfo = r.distributor_list;
                }
            });
        }

        $scope.getCacheQuery = function(cache) {
            $scope.pageNo = cache.content.page_no;
            $scope.pageSize = cache.content.page_size;
            $scope.name = cache.content.nick_name;
            $scope.phone = cache.content.phone;
            $scope.grade_id = cache.content.grade_id;
            $scope.agentInfo = cache.content.member_id;

            if (!cache.content.status) {
                $scope.chosedStatus = 0;
            }
        }

        //查询条件
        $scope.getWhere = function(query) {
            if ($scope.name) {
                query.content.nick_name = $scope.name;
            }
            if ($scope.phone) {
                query.content.phone = $scope.phone;
            }

            if ($scope.grade_id && $scope.grade_id != -2) {
                query.content.grade_id = $scope.grade_id;
            }

            if ($scope.agentInfo) {
                query.content.member_id = $scope.agentInfo;
            }

            return query;
        }

        //已选会员
        $scope.memberdata = function(memberdata) {
            // dhf.fx.distributor.update
            var data = {
                content: {
                    "store_id": $rootScope.store_id,
                    "user_id": memberdata.member_id,
                    "introduce": "商家添加"
                }
            };

            dataService.distributorUpdate(data).then(function(r) {
                if (r.errmsg == "ok") {
                    helper.myAlert("success", null, null, function() {
                        $scope.getDistributorOne();
                    });
                } else {
                    helper.myAlert("error:" + r.errmsg);
                }
            });
        }

        //手动添加上一级代理商
        $scope.addFatherDistributor = function(memberdata, user_id) {
            if (memberdata.member_id == user_id) {
                helper.myAlert("上级代理商不能和用户相同");
                return false;
            }
            var data = {
                content: {
                    "store_id": $rootScope.store_id,
                    "user_id": user_id,
                    "father_user_id": memberdata.member_id,
                }
            };

            dataService.distributorUpdate(data).then(function(r) {
                if (r.errmsg == "ok") {
                    helper.myAlert("success", null, null, function() {
                        $scope.getDistributorOne();
                    });
                } else {
                    helper.myAlert("error:" + r.errmsg);
                }
            });
        }

        //清除上一级代理商
        $scope.clearFatherUser = function(user_id) {
            helper.myConfirm("确认删除吗？", function() {
                var data = {
                    content: {
                        "store_id": $rootScope.store_id,
                        "user_id": user_id,
                        "father_user_id": 0,
                    }
                };

                dataService.distributorUpdate(data).then(function(r) {
                    if (r.errmsg == "ok") {
                        helper.myAlert("success", null, null, function() {
                            $scope.getDistributorOne();
                        });
                    } else {
                        helper.myAlert("error:" + r.errmsg);
                        return false;
                    }
                });
            });
        }

        $scope.setupAction = function() {
            $rootScope.whiteListUser();

            $scope.getMinimum();
            $scope.fenxiaoState();
            $scope.fenxiaoAutoShenPi();
            $scope.fenxiaoAutoShenQing();
            $scope.foreverState();
        }

        //代理商审核
        $scope.infoAction = function() {
            $scope.pageSize = 10;
            $scope.chosedStatus = "S_ORDER_COMPLETED";

            $scope.distributor_id = $location.search().distributor_id;
            $scope.user_id = $location.search().user_id;

            if ($scope.distributor_id) {
                $scope.getDistributorOne();
                $scope.orderGet();
                $scope.orderamountGet();
            }
        }

        //代理商个人详情编辑
        $scope.upDistributorInfo = function() {
            var data = {};
            data.content = $scope.distributorInfo;

            dataService.distributorUpdate(data).then(function(r) {
                if (r.errmsg == "ok") {
                    helper.myAlert("success", null, null, function() {
                        $state.go("distributor.list");
                    });

                } else {
                    helper.myAlert("error:" + r.errmsg);
                    return false;
                }
            });
        }

        //订单列表
        $scope.orderGet = function(pageNo) {
            var query = {
                page_no: pageNo ? pageNo : "1",
                page_size: $scope.pageSize
            };
            query.query = {
                "member_id": $scope.user_id
            };

            if ($scope.chosedStatus && $scope.chosedStatus !== "All") {
                query.query.status = $scope.chosedStatus;
            }

            //门店
            if ($scope.store_id) {
                query.query.store_id = $rootScope.store_id;
            }

            dataService.orderGet(query).then(function(list) {
                if (list) {
                    $scope.orderslist = list.orders;
                    $scope.total_count = list.total_count;
                }
            });
        }

        //订单总金额
        $scope.orderamountGet = function() {
            var data = {
                "content": {
                    "store_id": $rootScope.store_id,
                    "member_id": $scope.user_id,
                }
            };

            if ($scope.chosedStatus && $scope.chosedStatus !== "All") {
                data.content.status = $scope.chosedStatus;
            }

            dataService.orderamountGet(data).then(function(result) {
                if (result.sum) {
                    $scope.orderamount = result.sum;
                }
            });
        }

        //是否同意授权 审核 check 2=批准 3=拒绝
        $scope.CheckUpdate = function(check, id, reason) {
            // console.error("sssssssssssssss", $scope.distributorInfo.grade_id, check);
            // return false;
            helper.myConfirm('confirm operation', function() {
                if (check == 2 && ($scope.distributorInfo.grade_id == undefined || $scope.distributorInfo.grade_id == -2)) {
                    helper.myAlert("请选择分销商等级再通过审核！");
                    return false;
                }
                var data = {
                    content: {
                        "distributor_id": id
                    }
                }

                data.content.check = check;
                data.content.reason = reason;

                if (check == 2) {
                    data.content.grade_id = $scope.distributorInfo.grade_id;
                }
                if (check == 3 && !reason) {
                    helper.myAlert("请添加拒绝理由！");
                    return false;
                }
                dataService.distributorUpdate(data).then(function(r) {
                    if (r.errmsg == "ok") {
                        helper.myAlert("success", null, null, function() {
                            $scope.getDistributorOne();
                        });
                    } else {
                        helper.myAlert("error:" + r.errmsg);
                    }
                });
            });
        }

        $scope.upgrade = function(grade_id, flag) {
            helper.myConfirm('confirm operation', function() {
                var data = {
                    content: {
                        "distributor_id": $scope.distributorInfo.distributor_id
                    }
                };

                if (flag) {
                    data.content.upgrade_id = grade_id;
                    data.content.upgrade = 1;
                } else {
                    data.content.grade_id = grade_id;
                }

                dataService.distributorUpdate(data).then(function(r) {
                    if (r.errmsg == "ok") {
                        helper.myAlert("success", null, null, function() {
                            // $scope.getList();
                            $state.go("distributor.list");
                        });
                    } else {
                        helper.myAlert("error:" + r.errmsg);
                    }
                });
            });
        }

        //设置最低额度
        $scope.setMinimum = function() {
            var keyName = "DISTRIBUTION_MINIMUM_" + $rootScope.store_id;

            var minimum = $scope.minimum;
            if (minimum == 0) {
                helper.myAlert("error:最低提现额度为0.01，不能设置为0");
                return false;
            }
            dataService.shopConfigOneByKey(keyName).then(function(a) {
                if (a) {
                    a.value = {
                        "minimum": minimum
                    };
                    dataService.shopConfigUpdate(a).then(function(result) {
                        if (result.shop_config_id) {
                            $scope.minimum = minimum;
                            helper.myAlert("success");
                        }
                    });
                } else {
                    dataService.shopConfigAdd({
                        field: keyName,
                        value: {
                            "minimum": minimum
                        }
                    }).then(function(result) {
                        if (result.shop_config_id) {
                            $scope.minimum = minimum;
                            helper.myAlert("success");
                        }
                    });
                }
            });
        }

        //最低提现金额
        $scope.getMinimum = function() {
            var keyName = "DISTRIBUTION_MINIMUM_" + $rootScope.store_id;
            dataService.shopConfigOneByKey(keyName).then(function(a) {
                if (a) {
                    dataService.shopConfigOne(a.shop_config_id).then(function(result) {
                        if (result.shop_config_id) {
                            var value = JSON.parse(result.value);
                            $scope.minimum = value.minimum;
                            $scope.defaultMinimum = false;
                        } else {
                            $scope.minimum = 0.01;
                            $scope.defaultMinimum = true;
                        }
                    });
                } else {
                    $scope.minimum = 0.01;
                    $scope.defaultMinimum = true;
                }
            });
        }

        //开启关闭分销功能
        $scope.operationDistribution = function(state) {
            var keyName = "DISTRIBUTION_STATE_" + $rootScope.store_id;
            dataService.shopConfigOneByKey(keyName).then(function(a) {
                if (a) {
                    a.value = {
                        "state": state
                    };
                    dataService.shopConfigUpdate(a).then(function(result) {
                        if (result.shop_config_id) {
                            $scope.state = state;
                        }
                    });
                } else {
                    dataService.shopConfigAdd({
                        field: keyName,
                        value: {
                            "state": state
                        }
                    }).then(function(result) {
                        if (result.shop_config_id) {
                            $scope.state = state;
                        }
                    });
                }
            });
        }

        //自动申请
        $scope.autoShenqing = function(state) {
            var keyName = "AUTO_APPLICATION_STATE_" + $rootScope.store_id;
            dataService.shopConfigOneByKey(keyName).then(function(a) {
                if (a) {
                    a.value = {
                        "state": state
                    };
                    dataService.shopConfigUpdate(a).then(function(result) {
                        if (result.shop_config_id) {
                            $scope.auto_state = state;
                        }
                    });
                } else {
                    dataService.shopConfigAdd({
                        field: keyName,
                        value: {
                            "state": state
                        }
                    }).then(function(result) {
                        if (result.shop_config_id) {
                            $scope.auto_state = state;
                        }
                    });
                }
            });
        }

        $scope.saveDistributionAutoShenHe = function() {
            var keyName = "DISTRIBUTION_AUTOSHENPI_" + $rootScope.store_id;

            dataService.shopConfigOneByKey(keyName).then(function(a) {
                if (a) {
                    a.value = {
                        "grade": $scope.autosp.grade
                    };
                    dataService.shopConfigUpdate(a).then(function(result) {
                        if (result.shop_config_id) {
                            $scope.autosp.grade = $scope.autosp.grade;
                            helper.myAlert("success");
                        }
                    });
                } else {
                    dataService.shopConfigAdd({
                        field: keyName,
                        value: {
                            "grade": $scope.autosp.grade
                        }
                    }).then(function(result) {
                        if (result.shop_config_id) {
                            $scope.autosp.grade = $scope.autosp.grade;
                            helper.myAlert("success");
                        }
                    });
                }
            });
        }

        //分销是否开启
        $scope.fenxiaoState = function() {
            var keyName = "DISTRIBUTION_STATE_" + $rootScope.store_id;
            dataService.shopConfigOneByKey(keyName).then(function(a) {
                if (a) {
                    dataService.shopConfigOne(a.shop_config_id).then(function(result) {
                        if (result.shop_config_id) {
                            var value = JSON.parse(result.value);
                            $scope.state = value.state;
                        } else {
                            $scope.state = 0;
                        }
                    });
                }
            });
        }

        //自动审批是否开启
        $scope.fenxiaoAutoShenPi = function() {
            var keyName = "DISTRIBUTION_AUTOSHENPI_" + $rootScope.store_id;
            $scope.autosp = {};
            dataService.shopConfigOneByKey(keyName).then(function(a) {
                if (a) {
                    dataService.shopConfigOne(a.shop_config_id).then(function(result) {
                        if (result.shop_config_id) {
                            var value = JSON.parse(result.value);
                            $scope.autosp.grade = value.grade;
                        } else {
                            $scope.autosp.grade = -1;
                        }
                    });
                }
            });
        }

        //自动申请是否开启
        $scope.fenxiaoAutoShenQing = function() {
            var keyName = "AUTO_APPLICATION_STATE_" + $rootScope.store_id;
            dataService.shopConfigOneByKey(keyName).then(function(a) {
                if (a) {
                    dataService.shopConfigOne(a.shop_config_id).then(function(result) {
                        if (result.shop_config_id) {
                            var value = JSON.parse(result.value);
                            $scope.auto_state = value.state;
                        } else {
                            $scope.auto_state = 0;
                        }
                    });
                }
            });
        }

        //永久分销是否开启
        $scope.foreverState = function() {
            var keyName = "FOREVERFX_STATE_" + $rootScope.store_id;
            dataService.shopConfigOneByKey(keyName).then(function(a) {
                if (a) {
                    dataService.shopConfigOne(a.shop_config_id).then(function(result) {
                        if (result.shop_config_id) {
                            var value = JSON.parse(result.value);
                            $scope.forever = value.state;
                        } else {
                            $scope.forever = 0;
                        }
                    });
                }
            });
        }

        //一劳永逸 用户永久分销
        $scope.autoForever = function(state) {
            var keyName = "FOREVERFX_STATE_" + $rootScope.store_id;
            dataService.shopConfigOneByKey(keyName).then(function(a) {
                if (a) {
                    a.value = {
                        "state": state
                    };
                    dataService.shopConfigUpdate(a).then(function(result) {
                        if (result.shop_config_id) {
                            $scope.forever = state;
                        }
                    });
                } else {
                    dataService.shopConfigAdd({
                        field: keyName,
                        value: {
                            "state": state
                        }
                    }).then(function(result) {
                        if (result.shop_config_id) {
                            $scope.forever = state;
                        }
                    });
                }
            });
        }

        //分销订单
        $scope.orderAction = function() {
            $scope.pageSize = 10;
            $scope.chosedStatus = "All";
            $scope.getOrderList();
        }

        //查询分销订单
        $scope.getOrderList = function(pageNo) {
            var query = {};
            var key = $rootScope.store_id + "distributorOrderGet";
            var cache = cacheService.get(key);
            //console.error("cache", cache);
            if (pageNo || !cache) {
                $scope.pageNo = pageNo ? pageNo : 1;
                $scope.pageSize = $scope.pageSize ? $scope.pageSize : 10;
                query = {
                    content: {
                        page_no: $scope.pageNo,
                        page_size: $scope.pageSize,
                        store_id: $rootScope.store_id
                    }
                };
                if ($scope.chosedStatus && $scope.chosedStatus !== "All") {
                    if ($scope.chosedStatus == 'weishenhe') {
                        query.content.status = 1;
                    }
                    if ($scope.chosedStatus == 'daijiesuan') {
                        query.content.status = 2;
                    }
                    if ($scope.chosedStatus == 'yijiesuan') {
                        query.content.status = 3;
                    }
                }

                // 创建时间
                if ($scope.start_time && $scope.end_time) {
                    query.content.start_time = $scope.start_time;
                    query.content.end_time = $scope.end_time;
                }

                // 订单编号
                if ($scope.order_id) {
                    query.content.order_id = $scope.order_id;
                }

                //选择代理商
                if ($scope.agentInfo) {
                    query.content.user_id = $scope.agentInfo;
                }
                cacheService.set(key, clone(query));
            } else {
                query = clone(cache);
                $scope.queryRcache(cache);
            }
            dataService.distributorOrderGet(query).then(function(r) {
                if (r.detail_list) {
                    $scope.detail_list = r.detail_list;
                    $scope.detail_count = r.total_count;
                }
            });
        }

        //缓存查询
        $scope.queryRcache = function(query) {
            if (query.content.status == 1) {
                $scope.chosedStatus == 'weishenhe';
            }
            if (query.content.status == 2) {
                $scope.chosedStatus == 'daijiesuan';
            }
            if (query.content.status == 3) {
                $scope.chosedStatus = 'yijiesuan';
            }
            // 创建时间
            if (query.content.start_time) {
                $scope.start_time = query.content.start_time;
            }

            if (query.content.end_time) {
                $scope.end_time = query.content.end_time;
            }
            // 订单编号
            if (query.content.order_id) {
                $scope.order_id = query.content.order_id;
            }
            $scope.pageNo = query.content.page_no;
            $scope.pageSize = query.content.pageSize;
        }

        //审核订单 //列出订单详情
        $scope.checkorderAction = function() {
            $scope.detail_id = $location.search().detail_id;

            var data = {
                content: {
                    "detail_id": $scope.detail_id,
                    "store_id": $rootScope.store_id,
                }
            };

            dataService.distributorOrderGet(data).then(function(r) {
                if (r.errmsg == "ok") {
                    $scope.detailData = r.detailData;
                } else {
                    helper.myAlert("error：" + r.errmsg);
                }
            });
        }

        //审核
        $scope.shenhe = function(detail_id) {
            helper.myConfirm('confirm operation', function() {
                var query = {
                    content: {
                        store_id: $rootScope.store_id,
                        detail_id: detail_id,
                        status: 2,
                    }
                };

                dataService.distributorOrderUpdate(query).then(function(r) {
                    if (r.errmsg == "ok") {
                        helper.myAlert("success", null, null, function() {
                            $state.go("distributor.order");
                        });
                    } else {
                        helper.myAlert("error：" + r.errmsg);
                    }
                });
            });
        }

        //结算记录
        $scope.clearingorderAction = function() {
            $scope.pageSize = 10;
            $scope.chosedClearingStatus = "all";
            $scope.getClearingOrderList();
        }

        //查询结算记录
        $scope.getClearingOrderList = function(pageNo) {
            var query = {
                content: {
                    page_no: pageNo ? pageNo : "1",
                    page_size: $scope.pageSize,
                    store_id: $rootScope.store_id
                }
            };

            if ($scope.chosedClearingStatus && $scope.chosedClearingStatus !== "all") {
                if ($scope.chosedClearingStatus == 'daishenhe') {
                    var a = 1;
                }
                if ($scope.chosedClearingStatus == 'daizhifu') {
                    var a = 2;
                }
                if ($scope.chosedClearingStatus == 'yizhifu') {
                    var a = 3;
                }
                if ($scope.chosedClearingStatus == 'shougongyizhifu') {
                    var a = 4;
                }
                if ($scope.chosedClearingStatus == 'yizuofei') {
                    var a = 5;
                }
                query.content.status = a;
            }

            // 创建时间
            if ($scope.start_time && $scope.end_time) {
                query.content.start_time = $scope.start_time;
                query.content.end_time = $scope.end_time;
            }

            // 订单编号
            if ($scope.order_id) {
                query.content.order_id = $scope.order_id;
            }

            dataService.distributorClearingOrderGet(query).then(function(r) {
                if (r.clearing_list) {
                    $scope.clearing_list = r.clearing_list;
                    $scope.total_count = r.total_count;
                }
            });
        }

        //结算明细记录
        $scope.clearingdetailAction = function() {
            $scope.pageSize = 10;

            $scope.clearing_id = $location.search().clearing_id;
            if ($scope.clearing_id) {
                $scope.getClearingDetailList();
            }
        }

        //查询结算明细
        $scope.getClearingDetailList = function(pageNo) {
            var query = {
                content: {
                    page_no: pageNo ? pageNo : "1",
                    page_size: $scope.pageSize,
                    store_id: $rootScope.store_id,
                    clearing_id: $scope.clearing_id,
                }
            };

            dataService.distributorClearingDetailGet(query).then(function(r) {
                if (r.clearing_detail_list) {
                    $scope.clearing_detail_list = r.clearing_detail_list;
                    $scope.total_count = r.total_count;
                }
            });
        }

        //审核结算记录
        $scope.shOrder = function(clearing_id) {
            helper.myConfirm('confirm operation', function() {
                var query = {
                    content: {
                        store_id: $rootScope.store_id,
                        clearing_id: clearing_id,
                        status: 2,
                    }
                };

                dataService.distributorClearingOrderUpdate(query).then(function(r) {
                    if (r.errmsg == "ok") {
                        helper.myAlert("success", null, null, function() {
                            $scope.getClearingOrderList();
                        });
                    } else {
                        helper.myAlert("error：" + r.errmsg);
                    }
                });
            });
        }

        //作废提现审核
        $scope.zuofeiOrder = function(clearing_id) {
            helper.myConfirm('confirm operation', function() {
                var query = {
                    content: {
                        store_id: $rootScope.store_id,
                        clearing_id: clearing_id,
                        status: 5,
                    }
                };

                dataService.distributorClearingOrderUpdate(query).then(function(r) {
                    if (r.errmsg == "ok") {
                        helper.myAlert("success", null, null, function() {
                            $scope.getClearingOrderList();
                        });
                    } else {
                        helper.myAlert("error：" + r.errmsg);
                    }
                });
            });
        }

        //支付结算记录
        $scope.zfOrder = function(clearing_id) {
            helper.myConfirm('confirm operation', function() {
                var query = {
                    content: {
                        store_id: $rootScope.store_id,
                        clearing_id: clearing_id,
                        status: 3,
                    }
                };

                dataService.distributorClearingOrderUpdate(query).then(function(r) {
                    if (r.errmsg == "ok") {
                        helper.myAlert("success", null, null, function() {
                            $scope.getClearingOrderList();
                        });
                    } else {
                        helper.myAlert("error：" + r.errmsg);
                        return false;
                    }
                });
            });
        }

        //手工支付佣金结算
        $scope.sgOrder = function(clearing_id) {
            helper.myConfirm('确定手工支付佣金么？确定之后将从线下支付佣金', function() {
                var query = {
                    store_id: $rootScope.store_id,
                    clearing_id: clearing_id,
                    status: 4
                };

                dataService.manualClearingOrderUpdate(query).then(function(r) {
                    if (r.errmsg == "ok") {
                        helper.myAlert("success", null, null, function() {
                            $scope.getClearingOrderList();
                        });
                    } else {
                        helper.myAlert("error：" + r.errmsg);
                        return false;
                    }
                });
            });
        }

        //结算
        $scope.jiesuan = function(detail_id) {
            var query = {
                content: {
                    store_id: $rootScope.store_id,
                    detail_id: detail_id,
                    status: 3,
                }
            };

            dataService.distributorOrderUpdate(query).then(function(r) {
                if (r.errmsg == "ok") {
                    helper.myAlert("success", null, null, function() {
                        $state.go("distributor.order");
                    });
                } else {
                    helper.myAlert("error：" + r.errmsg);
                }
            });
        }

        // 待结算订单-直接付款
        $scope.payDirectly = function(detail_id, order_id) {
            helper.myConfirm("确定直接付钱么？", function() {
                var query = {
                    store_id: $rootScope.store_id,
                    detail_id: detail_id,
                    order_id: order_id
                };

                dataService.distributorPayDirectly(query).then(function(r) {
                    if (r.Msg == "ok") {
                        helper.myAlert("success");
                        $scope.getClearingOrderList(1);
                    } else {
                        helper.myAlert("error：" + r.Msg);
                    }
                });
            });
        }
    }
})();